<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 搜索和添加区域 -->
      <div class="operation-area">
        <el-form :inline="true" :model="query">
          <el-form-item label="试卷名称">
            <el-input clearable v-model="query.name" placeholder="请输入试卷名称" />
          </el-form-item>
          <el-form-item label="省份">
            <el-input style="width: 100px" clearable v-model="query.province" placeholder="请输入省份" />
          </el-form-item>
          <el-form-item label="年份">
            <el-input style="width: 100px" clearable v-model="query.years" placeholder="请输入年份" />
          </el-form-item>
          <el-form-item label="试卷类型">
            <el-select style="width: 150px" v-model="query.sort" placeholder="请选择试卷类型" clearable>
              <el-option label="公考行测" value="公考行测" />
              <el-option label="事业编职测" value="事业编职测" />
              <el-option label="公共基础" value="公共基础" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="display: flex;gap: 0px;">
        <!-- 导入注意事项 -->
        <el-button type="danger" @click="openDraw">导入注意事项（必读）</el-button>
        <el-button type="success" @click="downloadFile">导入案例下载</el-button>
        <el-button type="success" @click="openDSanf">第三方导入</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" style="width: 100%; margin-top: 20px" border stripe height="calc(100vh - 320px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#000' }">
        <el-table-column width="300" prop="name" align="left" label="试卷名称" />
        <el-table-column prop="province" align="center" width="160" label="省份">
          <template #default="scope">
            <el-tag style="margin-right: 5px" v-for="item in scope.row.province.split(',')" effect="dark" type="info"
              size="small">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="years" align="center" label="年份" width="80" show-overflow-tooltip />
        <el-table-column prop="sort" align="center" label="试卷类型" width="100">
        </el-table-column>
        <el-table-column prop="difficultyLevel" align="center" label="难度系数" width="90">
          <!-- <template #default="scope">
						<el-tag v-if="scope.row.difficultyLevel" effect="dark" type="info"  size="small">{{ scope.row.difficultyLevel }}</el-tag>
					</template> -->
        </el-table-column>
        <!-- status -->
        <el-table-column prop="status" align="center" label="状态" width="140">
          <template #default="scope">
            <el-switch @change="statusChange($event, scope.row)" :active-value="1" :inactive-value="0"
              v-model="scope.row.status" active-text="启用" inactive-text="禁用"></el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="试卷预览" width="100">
          <template #default="scope">
            <el-button type="success" size="small" @click="handleShowDetail(scope.row)">试卷预览</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center">
          <template #default="scope">
            <!-- <el-button type="info" size="small" @click="handleShow(scope.row)"
							>关联题目</el-button
						> -->
            <div style="display: flex;gap: 10px;justify-content: center ;">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="small" :loading="scope.row.uploadLoading" type="info"
                @click="openImportDialog(scope.row)">导入</el-button>
              <el-dropdown style="margin-left: 10px" @command="command => handleDownload(scope.row, command)">
                <el-button type="warning" size="small" :loading="scope.row.downloadLoading">
                  下载<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="1">下载题目</el-dropdown-item>
                    <el-dropdown-item command="2">下载解析</el-dropdown-item>
                    <el-dropdown-item command="3">下载题目及解析</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

            </div>

          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination v-model:current-page="query.pageNum" v-model:page-size="query.pageSize"
          :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <!-- 添加/编辑对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加试卷' : '编辑试卷'" :close-on-click-modal="false"
        width="800px">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="试卷名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="试卷类型" prop="sort">
            <el-radio-group v-model="form.sort">
              <el-radio-button label="公考行测">公考行测</el-radio-button>
              <el-radio-button label="事业编职测">事业编职测</el-radio-button>
              <el-radio-button label="公共基础">公共基础</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="省份" prop="province">
            <div class="province-checkbox-group">
              <el-checkbox v-for="(item, index) in provienceOptions" :key="item" v-model="form.province" :label="item"
                style="width: 16.66%; margin-right: 0; margin-bottom: 10px">
                {{ item }}
              </el-checkbox>
            </div>
          </el-form-item>
          <el-form-item label="年份" prop="years">
            <el-input v-model="form.years" type="number" />
          </el-form-item>

          <el-form-item label="难度系数" prop="difficultyLevel">
            <el-input v-model="form.difficultyLevel" placeholder="请输入难度系数" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-drawer v-model="viewDialogVisible" title="关联题目" size="60%" :destroy-on-close="true">
        <Papertimu v-if="viewDialogVisible" :shijuanId="shijuanId" />
      </el-drawer>
      <!-- 整体试卷 -->
      <el-drawer custom-class="shijuanDetaildrawer" :with-header="false" v-model="viewDialogVisibleDetail" title="试卷查看"
        size="100%" :destroy-on-close="true">
        <shijuanDetail v-if="viewDialogVisibleDetail" :shijuanId="shijuanId" :source="source" />
        <div class="close-btn" @click="viewDialogVisibleDetail = false">
          <el-icon>
            <Close />
          </el-icon>
        </div>
      </el-drawer>

      <!-- 导入弹窗 -->
      <el-dialog v-model="importDialogVisible" title="导入试卷" width="800px">
        <!-- 导入将导致试卷之前的所有数据 -->
        <el-alert title="注意：导入将导致试卷之前的所有数据被覆盖，是否继续？" type="warning" show-icon style="margin-bottom: 20px" />
        <!-- 上传文件 -->
        <el-upload :file-list="fileListExcel" :ref="(el) => setUploadRef(currentRow?.id, el)"
          :on-change="(file, fileList) => handleUploadChange(currentRow, file, fileList)" class="upload-demo"
          :action="server" :limit="1" accept=".doc,.docx"
          :on-success="(res, file, fileList) => handleUploadSuccess(currentRow, res, file, fileList)" :data="{
            paperId: currentRow?.id
          }" :show-file-list="true">
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">请上传 .doc/.docx 格式的文件</div>
          </template>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="importDialogVisible = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
  <el-drawer title="试卷导入注意事项" v-model="Attenctdrawer" size="60%" destroy-on-close>
    <attenceThing />
  </el-drawer>
  <el-drawer title="第三方导入" v-model="dSanFangDrawer" size="60%" destroy-on-close>
    <DSanfang />
  </el-drawer>

</template>

<script setup lang="ts">
import { findAll, addpaper, deldpaper, generateWord } from '../api/index';
import attenceThing from './attenceThing.vue';
import { ref, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import Papertimu from './Papertimu.vue';
import shijuanDetail from './shijuanDetail.vue';
import { Close, ArrowDown } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';
const downloadLoading = ref(false);
import { serverDefaultCfg } from '@/common/http/config';
import { pa } from 'element-plus/es/locale';
import { add } from 'xe-utils';
import DSanfang from './DSanfang.vue';
const server = serverDefaultCfg.baseURL + '/question/upload'
// 表格数据
const uploadRefs = ref({});
const importDialogVisible = ref(false);
const currentRow = ref(null);

const tableData = ref([]);
const total = ref(0);
const viewDialogVisibleDetail = ref(false);
const fileListExcel = ref([]);
const Attenctdrawer = ref(false);
const dSanFangDrawer = ref(false);
const openDraw = () => {
  Attenctdrawer.value = true;
}
const openDSanf = () => {
  dSanFangDrawer.value = true;
}
const downloadFile = () => {
  // window.open('/files/试卷导入案例.docx');
  // https://gktm123.oss-cn-beijing.aliyuncs.com/image/c5b44a22ff9141a690332befd4a8d49c.docx
  window.open('https://gktm123.oss-cn-beijing.aliyuncs.com/image/c5b44a22ff9141a690332befd4a8d49c.docx');
}
const query = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  province: '',
  years: '',
  sort: '',
  difficultyLevel: '',
  status: -1
});
let defalutProvicexc = [
  '国考',
  '国考模拟卷',
  '省考模拟卷',
  '选调生',
  '安徽',
  '北京',
  '重庆',
  '福建',
  '甘肃',
  '广东',
  '广西',
  '贵州',
  '海南',
  '河北',
  '河南',
  '黑龙江',
  '湖北',
  '湖南',
  '吉林',
  '江苏',
  '江西',
  '辽宁',
  '内蒙古',
  '宁夏',
  '青海',
  '山东',
  '山西',
  '陕西',
  '上海',
  '四川',
  '天津',
  '西藏',
  '新疆',
  '云南',
  '浙江'
];
let defalutProviceshiye = [
  '联考A类',
  '联考B类',
  '联考C类',
  '联考D类',
  '联考E类',
  '国考',
  '安徽',
  '北京',
  '重庆',
  '福建',
  '甘肃',
  '广东',
  '广西',
  '贵州',
  '海南',
  '河北',
  '河南',
  '黑龙江',
  '湖北',
  '湖南',
  '吉林',
  '江苏',
  '江西',
  '辽宁',
  '内蒙古',
  '宁夏',
  '青海',
  '山东',
  '山西',
  '陕西',
  '上海',
  '四川',
  '天津',
  '西藏',
  '新疆',
  '云南',
  '浙江'
];
const statusChange = (e, row) => {
  console.log(row, e);
  addpaper({ id: row.id, status: e }).then(res => {
    if (res.code === 200) {
      ElMessage.success('状态更新成功');
      getTableData();
    } else {
      ElMessage.error(res.msg || '状态更新失败');
    }
  });
};
const setUploadRef = (id, el) => {
  if (el) {
    uploadRefs.value[id] = el
  } else {
    // 可选：组件卸载时清除，避免内存泄漏
    delete uploadRefs.value[id]
  }
}
const handleUploadChange = row => {
  row.uploadLoading = true;
};
const handleUploadSuccess = (row, response) => {
  console.log(response);
  if (response.code === 200) {
    // ElMessage.success(response.data || '导入成功');
    // ElNotification({
    //   title: '成功',
    //   message: response.data || '导入成功',
    //   type: 'success',
    //   duration: 0
    // });
    ElMessageBox.alert(response.data || '导入成功', '标题名称', {
      confirmButtonText: '确定',
    });
    row.uploadLoading = false;
    // 重置上传组件
    const uploadRef = uploadRefs.value[row.id]
    setTimeout(() => {
      uploadRef.value?.clearFiles();
    }, 1000);
    getTableData();
    fileListExcel.value = [];
    importDialogVisible.value = false;

  } else {
    ElMessage.error(response.data || '导入失败');
  }
};

// 打开导入弹窗
const openImportDialog = (row) => {
  currentRow.value = row;
  importDialogVisible.value = true;
};

const provienceOptions = ref(defalutProvicexc);
const handleDownload = (row, type) => {
  row.downloadLoading = true;
  console.log(row, type);
  generateWord(row.id, type).then(res => {
    console.log(res);

    row.downloadLoading = false;
    const url = window.URL.createObjectURL(res);
    const a = document.createElement('a');
    a.href = url;
    a.download = row.name + '.docx';
    a.click();
  });
  // 这里添加下载逻辑，根据type的值（1,2,3）来处理不同的下载情况
};

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const formRef = ref<FormInstance | null>(null);

// 表单数据
const form = reactive({
  name: '',
  province: [] as string[],
  years: '',
  sort: '行测',
  id: undefined as number | undefined,
  difficultyLevel: ''
});

// 单验证规则
const rules = {
  name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
  years: [{ required: true, message: '请输入年份', trigger: 'blur' }],
  sort: [{ required: true, message: '请选择试卷类型', trigger: 'change' }]
};

const viewDialogVisible = ref(false);
const shijuanId = ref('');
const handleShow = row => {
  shijuanId.value = row.id;
  viewDialogVisible.value = true;
};
// 获取表格数据
const getTableData = async () => {
  // 这里添加实际的API调用
  // const res = await api.getShijuanList({
  //   page: currentPage.value,
  //   pageSize: pageSize.value
  // })
  // tableData.value = res.data.list
  // total.value = res.data.total
  // tableData.value = []
  const res = await findAll(query.value);
  tableData.value = res.data.records;
  total.value = res.data.total;
};

// 处理页码改变
const handleCurrentChange = val => {
  query.value.pageNum = val;
  getTableData();
};

// 处理每页条数改变
const handleSizeChange = val => {
  query.value.pageSize = val;
  getTableData();
};

// 添加按钮点击
const handleAdd = () => {
  dialogType.value = 'add';
  form.name = '';
  form.province = [];
  form.years = new Date().getFullYear().toString();
  form.sort = '行测';
  form.difficultyLevel = '';
  form.id = undefined;

  dialogVisible.value = true;
};

// 编辑按钮点击
const handleEdit = row => {
  dialogType.value = 'edit';
  form.name = row.name;
  form.province = row.province.split(',');
  form.years = row.years;
  form.sort = row.sort;
  form.difficultyLevel = row.difficultyLevel;
  form.id = row.id;
  dialogVisible.value = true;
};

// 删除按钮点击
const handleDelete = row => {
  ElMessageBox.confirm('确认删除该试卷吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    deldpaper(row.id).then(Res => {
      ElMessage.success('删除成功');
      getTableData();
    });
  }).catch(() => {
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async valid => {
    if (valid) {
      const submitForm = { ...form };
      submitForm.province = submitForm.province.join(',');
      // 新增和编辑是同一个请求
      const res = await addpaper(submitForm);
      if (res.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
        dialogVisible.value = false;
        getTableData();
      } else {
        ElMessage.error(res.msg);
      }
    }
  });
};

// 添加搜索处函数
const handleSearch = () => {
  query.value.pageNum = 1;
  getTableData();
};

// 重置查询条件
const resetQuery = () => {
  query.value = {
    pageNum: 1,
    pageSize: 10,
    name: '',
    province: '',
    years: '',
    sort: '',
    difficultyLevel: ''
  };
  getTableData();
};

// 初始化
getTableData();
const source = ref('');
const handleShowDetail = row => {
  viewDialogVisibleDetail.value = true;
  console.log(viewDialogVisibleDetail.value);
  shijuanId.value = row.id;
  source.value = row.name;
};

// 恢复 watch
watch(
  () => {
    return form.sort;
  },
  (newValue, oldValue) => {
    console.log(newValue);

    if (newValue === '事业编职测') {
      provienceOptions.value = defalutProviceshiye;
    } else {
      provienceOptions.value = defalutProvicexc;
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.operation-area {
  margin-bottom: 20px;

  .el-form {

    // 当表单项换行时，保持合理间距
    .el-form-item {
      margin-bottom: 18px;
      margin-right: 18px;
    }
  }
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.shijuanDetaildrawer,
:deep(.el-drawer__body) {
  overflow: hidden;
}

:deep(.el-drawer__body) {
  overflow: hidden;
}

.close-btn {
  position: fixed;
  top: 24px;
  right: 24px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(4px);
  cursor: pointer;
  transition: all 0.25s ease;
  z-index: 100;

  .el-icon {
    font-size: 24px;
    color: #fff;
    transition: transform 0.25s ease;
  }

  &:hover {
    background: rgba(0, 0, 0, 0.4);

    .el-icon {
      transform: rotate(90deg);
    }
  }
}

.province-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  width: 100%;

  :deep(.el-checkbox) {
    margin-right: 0;

    .el-checkbox__label {
      padding-left: 6px;
    }
  }
}
</style>
